package icu.luoxi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import icu.luoxi.common.BusinessException;
import icu.luoxi.model.entity.User;
import icu.luoxi.mapper.master.UserMapper;
import icu.luoxi.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.luoxi.utils.SHA256Utils;
import icu.luoxi.utils.UUIDGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 洛希极限
 * @since 2025-05-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${default-password}")
    private String defaultPassword;

    @Resource
    private UserMapper userMapper;

    @Override
    public String createUser(User user) {
        if (user == null) {
            throw new BusinessException(400,"用户信息不能为空");
        }
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()){
            throw new BusinessException(400,"用户名不能为空");
        }
        User one = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (one != null){
            throw new BusinessException(400,"用户名已存在");
        }
        user.setId(UUIDGenerator.getOne());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        String password = user.getPassword();
        if (password == null || password.trim().isEmpty()) {
            // 默认密码
            password = defaultPassword;
        }
        user.setPassword(SHA256Utils.encrypt(password));
        int i = userMapper.insert(user);
        return i > 0 ? user.getId() : null;
    }
}
